package cn.wizzer.app.web.commons.doc;

import java.io.*;
import java.net.*;


public class OfficeOnlineConverter {
    public static void main(String[] args) throws UnsupportedEncodingException {
        // 指定要下载的 URL 和目标文件路径
        String wopiSrc = "http://192.168.40.1/platform/wopi/files/e62bfad845cd4896a049541aad8c8d04.docx";
        String timestamp = String.valueOf(System.currentTimeMillis());
        String urlString = String.format("http://192.168.40.132/wv/WordViewer/Document.pdf?WOPIsrc=%s&z=%s&type=accesspdf",
                java.net.URLEncoder.encode(wopiSrc, "UTF-8"), timestamp);
        String outputFilePath = "D://docs/report/2024/12/14/output.pdf";  // 替换为你想保存 PDF 的路径

        try {
            // 创建 URL 对象
            URL url = new URL(urlString);
            // 打开连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(5000);  // 设置连接超时
            connection.setReadTimeout(5000);     // 设置读取超时

            // 检查响应代码
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                // 获取输入流
                InputStream inputStream = new BufferedInputStream(connection.getInputStream());
                // 创建输出流
                FileOutputStream fileOutputStream = new FileOutputStream(outputFilePath);

                byte[] buffer = new byte[4096];
                int bytesRead;
                // 将输入流中的数据写入到文件中
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    fileOutputStream.write(buffer, 0, bytesRead);
                }

                // 关闭流
                fileOutputStream.close();
                inputStream.close();

                System.out.println("PDF 文件已成功下载并保存到: " + outputFilePath);
            } else {
                System.out.println("请求失败，HTTP 响应代码: " + responseCode);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
